package org.jsola.contract.core;

import org.apache.ibatis.session.SqlSessionFactory;
import org.jsola.autoconfigure.orm.mybatis.MybatisConfigurationSupport;
import org.jsola.contract.service.IContractPathService;
import org.jsola.contract.service.ISynchronizeContractService;
import org.jsola.contract.service.ITemplateContentService;
import org.jsola.contract.service.impl.ContractPathServiceImpl;
import org.jsola.contract.service.impl.SynchronizeContractServiceImpl;
import org.jsola.contract.service.impl.TemplateContentServiceImpl;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.annotation.MapperScan;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

import static org.jsola.contract.constant.ContractConstants.*;
import static org.jsola.contract.constant.ContractConstants.CONTRACT_CONTRACT_PATH;

/**
 * @author JanusMix
 */
@Configuration
@EnableConfigurationProperties(ContractProperties.class)
@MapperScan(basePackages = "org.jsola.contract.dao", sqlSessionFactoryRef = SQL_SESSION_FACTORY_BEAN_NAME)
@AutoConfigureBefore(MybatisAutoConfiguration.class)
public class ContractAutoConfiguration {

    @Bean(name = SQL_SESSION_FACTORY_BEAN_NAME)
    @ConditionalOnMissingBean(name = SQL_SESSION_FACTORY_BEAN_NAME)
    public SqlSessionFactory contractSqlSessionFactory(DataSource datasource, MybatisConfigurationSupport mybatisConfigurationSupport) throws Exception {
        return mybatisConfigurationSupport.build(datasource);
    }

    @Bean(name = TX)
    @ConditionalOnMissingBean(name = TX)
    public DataSourceTransactionManager contractTx(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = CONTRACT_CONTRACT_PATH)
    @ConditionalOnMissingBean
    public IContractPathService getContractPathServiceImpl() {
        return new ContractPathServiceImpl();
    }

    @Bean(name = CONTRACT_TEMPLATE_CONTENT_SERVICE)
    @ConditionalOnMissingBean
    public ITemplateContentService getTemplateContentServiceImpl() {
        return new TemplateContentServiceImpl();
    }

    @Bean()
    @ConditionalOnMissingBean
    public ISynchronizeContractService getSynchronizeContractServiceImpl() {
        return new SynchronizeContractServiceImpl();
    }

}
